<template>
    <div class="app-container">
        <div style="display: flex">
            <el-form :model="datess" ref="queryForm" size="small" :inline="true" v-show="showSearch">
              <el-form-item label="开始时间">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="datess.startTime" type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="datess.endTime" type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="zhenghandleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
  
          <el-table v-loading="loading" :data="zhengroleList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <!-- <el-table-column fixed label="客服名称" prop="serviceName" /> -->
            <el-table-column label="月度成交价" prop="totalTransactionPrice" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="应收" prop="totalBillReceivable" :show-overflow-tooltip="true" width="150" />
  
            <el-table-column label="实收" prop="totalOfficialReceipts" />
  
            <el-table-column label="毛利" prop="grossMargin" />
            <el-table-column label="写手总报酬" width="120" prop="totalTeacherTotalPrice" />
            <el-table-column label="应退款" prop="totalCustomerRefundAmount" />
            <el-table-column label="实退款" prop="totalCustomerRefundableAmount" />
  
            <el-table-column label="应收应退比例" width="120" prop="ratio" />
            <el-table-column label="退款调整后应收利润" width="150" prop="adjustedProfitReceivable" />
            <el-table-column label="退款调整后实收利润" width="150" prop="adjustedProfit" />
            <el-table-column label="平均报价时间" width="120" prop="avgQuotationTime" />
            <el-table-column label="净利润" prop="netMargin" />
  
            
            <el-table-column label="客户数" prop="customerCount" />
           
            
  
            <el-table-column label="新客户数量" width="120" prop="customerNickname" />
            <el-table-column label="未收金额" prop="outstandingAmount" />
            <el-table-column label="属性" prop="attributeList" />
            <el-table-column label="订单量" prop="orderCount" />
            <el-table-column label="成交价" prop="totalTransactionPrice" />
            <el-table-column label="客户数" prop="customerCount" />
            <el-table-column label="毛利率" prop="grossProfitRate" />
            <el-table-column label="低档占比" prop="lowRate" />
            <el-table-column label="中档占比" prop="middleRate" />
            <el-table-column label="高档占比" prop="highRate" />
            <el-table-column label="挂科数" prop="failCount" />
            <el-table-column label="挂科率" prop="failRate" />
            <el-table-column label="保分达成数" width="100" prop="guaranteeSucceedCount" />
            <el-table-column label="保分达成率" width="100" prop="guaranteeRate" />
            <el-table-column label="客户平均下单量" width="120" prop="customerAvgCount" />
            <el-table-column label="老师评分均值" width="100" prop="teacherScore" />
            <el-table-column label="客服评分均值" width="100" prop="serviceScore" />
            <el-table-column label="及时交稿率" width="100" prop="timelyDeliveryRate" />











            
          </el-table>
          <tab :zhengroleList="zhengroleList" />
    </div>
  </template>
  
  <script>
  import { getRole } from "@/api/system/role";
  import tab from './tab.vue'
  import { chulikesu, getjyue, getjyues, zhenggetjyues } from "@/api/new";
  import { treeselect as menuTreeselect } from "@/api/system/menu";
  
  export default {
    name: "Role",
    dicts: ["sys_normal_disable"],
  
    components: { tab },
    data() {
      return {
        // 遮罩层
        loading: true,
        activeName: "first",
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        zhengroleList: [],
        wanjiekopng: false,
        // 弹出层标题
        title: "",
        kesuwanfrom: {
          orderId: "",
          disposeResult: "",
        },
        kesuwanfromre: {
          disposeResult: [
            { required: true, message: "处理结果不能为空", trigger: "blur" },
          ],
        },
        datess: {
          startTime:this.getOneMonthAgoDateTime(),endTime:this.getCurrentDateTime()
        },
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        menuExpand: false,
        menuNodeAll: false,
        deptExpand: true,
        deptNodeAll: false,
        // 日期范围
        dateRange: [],
        // 数据范围选项
        secvalue: "",
        // 菜单列表
        menuOptions: [],
        // 部门列表
        deptOptions: [],
        options: [
          {
            value: "按月查询",
            label: "按月查询",
          },
          {
            value: "按年查询",
            label: "按年查询",
          },
        ],
        // 查询参数
        queryParams: {
          startTime: '',
          endTime: '',
          pageNo: 1,
          pageSize: 10,
        },
        dates: {
          month: "",
          years: "",
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label",
        },
        // 表单校验
        rules: {
          roleName: [
            { required: true, message: "角色名称不能为空", trigger: "blur" },
          ],
          roleKey: [
            { required: true, message: "权限字符不能为空", trigger: "blur" },
          ],
          roleSort: [
            { required: true, message: "角色顺序不能为空", trigger: "blur" },
          ],
        },
      };
    },
    created() {
      this.zhenghandleQuery()
    },
    methods: {

      getOneMonthAgoDateTime() {
      const now = new Date();
      const monthAgo = new Date(now);
      monthAgo.setMonth(now.getMonth() - 1);
 
      // 处理月份回滚导致日期超出范围的情况（例如：从1月31日到去年12月的情况）
      // 如果日期回滚后小于当前月份的第一天（考虑到月份和年份可能都变了），则设置为该月的第一天
      if (monthAgo.getMonth() + 1 !== now.getMonth() || monthAgo.getFullYear() !== now.getFullYear()) {
        monthAgo.setDate(1);
        // 如果需要设置为该月的第一天00:00:00，则不需要额外处理时间部分
        // 因为JavaScript Date对象在设置月份时会自动处理时间部分（即不会保留原时间）
      } else {
        // 如果日期没有回滚（例如：从2月15日到1月15日），则可能需要保留原时间或设置为某个固定时间
        // 这里我们保留原时间的小时、分钟和秒（如果需要的话）
        // 但由于我们是从“现在”开始计算的，所以时间部分已经是00:00:00（如果我们假设now是在一天的开始创建的）
        // 如果不是，你可以手动设置时间部分，比如：
        // monthAgo.setHours(0, 0, 0, 0); // 设置为00:00:00.000
      }
 
      // 格式化日期时间为字符串
      const year = monthAgo.getFullYear();
      const month = String(monthAgo.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
      const day = String(monthAgo.getDate()).padStart(2, '0');
      const hours = String(monthAgo.getHours()).padStart(2, '0');
      const minutes = String(monthAgo.getMinutes()).padStart(2, '0');
      const seconds = String(monthAgo.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
      getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 月份从0开始，需要+1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
      dangyue() {
        // 获取当前日期
        const now = new Date();
  
        // 获取年份，getFullYear()方法会返回一个四位的年份
        const year = now.getFullYear();
  
        // 获取月份，getMonth()方法返回的月份是从0开始的，所以需要加1
        const month = (now.getMonth() + 1).toString().padStart(2, "0");
  
        // 使用模板字符串或者字符串连接来组合年份和月份
        // return `${year}-${month}`;
        this.dates.month = `${year}-${month}`;
        this.getList();
      },
    
      guanbishoukan() {
        this.kesuwanfrom = {
          orderId: "",
          disposeResult: "",
        };
      },
      wanjjie() {
        this.$refs["wanjie"].validate((valid) => {
          if (valid) {
            chulikesu(this.kesuwanfrom).then(() => {
              this.wanjiekopng = false;
              this.getList();
              this.$modal.msgSuccess("处理成功");
            });
          }
        });
      },
  
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        getjyue({ date: this.dates.month }).then((response) => {
          this.roleList = response.data;
          this.loading = false;
        });
      },
      getLists() {
        this.loading = true;
        getjyues({ date: this.dates.years }).then((response) => {
          this.roleList = response.data;
          this.loading = false;
        });
      },
  
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys();
        // 半选中的部门节点
        let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      zhenghandleQuery() {
        this.zhenggetList();
      },
      zhenggetList() {
        this.loading = true;
        zhenggetjyues(this.datess).then((response) => {
          this.zhengroleList = [response.data];
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNo = 1;
        this.getList();
      },
      handleQuerys() {
        this.queryParams.pageNo = 1;
        this.getLists();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.datess = {
          month: "",
          years: "",
        };
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.orderId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleDataScope":
            this.handleDataScope(row);
            break;
          case "handleAuthUser":
            this.handleAuthUser(row);
            break;
          default:
            break;
        }
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type == "menu") {
          let treeList = this.menuOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
          }
        } else if (type == "dept") {
          let treeList = this.deptOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        if (type == "menu") {
          this.$refs.menu.setCheckhandleAddedNodes(value ? this.menuOptions : []);
        } else if (type == "dept") {
          this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
        }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type == "menu") {
          this.form.menuCheckStrictly = value ? true : false;
        } else if (type == "dept") {
          this.form.deptCheckStrictly = value ? true : false;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getMenuTreeselect();
        this.open = true;
        this.title = "添加角色";
      },
  
      /** 修改按钮操作 */
      handleUpdate(row) {
        console.log(this.ids);
        this.kesuwanfrom.orderId = row.orderId || this.ids[0];
        this.wanjiekopng = true;
        this.title = "处理";
      },
      /** 选择角色权限范围触发 */
      dataScopeSelectChange(value) {
        if (value !== "2") {
          this.$refs.dept.setCheckedKeys([]);
        }
      },
      /** 分配数据权限操作 */
      handleDataScope(row) {
        this.reset();
        const deptTreeSelect = this.getDeptTree(row.complaintId);
        getRole(row.complaintId).then((response) => {
          this.form = response.data;
          this.openDataScope = true;
          this.$nextTick(() => {
            deptTreeSelect.then((res) => {
              this.$refs.dept.setCheckedKeys(res.checkedKeys);
            });
          });
          this.title = "分配数据权限";
        });
      },
      /** 分配用户操作 */
      handleAuthUser: function (row) {
        const complaintId = row.complaintId;
        this.$router.push("/system/role-auth/user/" + complaintId);
      },
  
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "system/role/export",
          {
            ...this.queryParams,
          },
          `role_${new Date().getTime()}.xlsx`
        );
      },
    },
  };
  </script>
  